package net.cloudcodex.client.character.presenter;

import net.cloudcodex.client.CloudCodexEventBus;
import net.cloudcodex.client.campaign.view.CampaignsView.Message;
import net.cloudcodex.client.character.view.CharacterPlayerInvitationView;
import net.cloudcodex.client.character.view.CharacterPlayerInvitationViewImpl;
import net.cloudcodex.client.util.ClientUtils;
import net.cloudcodex.client.util.rpc.SuccessCallback;
import net.cloudcodex.shared.dto.Result;
import net.cloudcodex.shared.dto.campaign.character.CharacterHeaderDTO;
import net.cloudcodex.shared.dto.home.CampaignSummaryDTO;
import net.cloudcodex.shared.rpc.CampaignRPCAsync;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.inject.Inject;
import com.mvp4g.client.annotation.Presenter;
import com.mvp4g.client.presenter.BasePresenter;

@Presenter(view = CharacterPlayerInvitationViewImpl.class)
public class CharacterPlayerInvitationPresenter extends
		BasePresenter<CharacterPlayerInvitationView, CloudCodexEventBus> {
	private final Message message;
	// private boolean isViewInit = false;
	private CampaignSummaryDTO campaignSummaryDTO;
	private CampaignRPCAsync campaignService;

	@Inject
	public CharacterPlayerInvitationPresenter(Message pMessage,
			CampaignRPCAsync campaignService) {
		this.message = pMessage;
		this.campaignService = campaignService;
	}

	@Override
	public void bind() {

		this.view.getInviteButton().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				String characterName = getValue(view.getName());
				String email = getValue(view.getMail());
				// String description = getValue(view.getDescription());
				campaignService.inviteToCampaign(campaignSummaryDTO.getId(),
						email, characterName,
						new SuccessCallback<Result<CharacterHeaderDTO>>() {

							@Override
							public void onSuccess(
									Result<CharacterHeaderDTO> result) {
								
								if (!result.hasErrors()){
									eventBus.addNewCharacterInCampaign(
											campaignSummaryDTO.getId(),
											result.getData());
								}
							}
						});
				view.hidePopup();
			}

			private String getValue(String text) {

				if (!ClientUtils.isBlankOrNull(text)) {
					return text;
				}
				return null;
			}
		});

		this.view.getCancelButton().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {

				view.hidePopup();
			}
		});

	}

	public void display() {
		// if (!isViewInit) {
		this.view.initView();
		// isViewInit = true;
		// }
		this.view.clearView();
		this.view.showPopup();
	}

	public void onInviteNewPlayer(CampaignSummaryDTO campaignSummaryDTO) {
		this.campaignSummaryDTO = campaignSummaryDTO;
		this.display();
	}

}
